﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using MSP.Business.UserManagement;
using MSP.Data.Domain;
using MSP.UI.Helpers;
using System.IO;
using DevExpress.XtraEditors.DXErrorProvider;
using MSP.Business.CustomerManagement;

namespace MSP.UI.Forms
{
    public partial class xfrmCustomers : DevExpress.XtraEditors.XtraForm
    {
        CustomerManager customerManager = new CustomerManager();
        CurrencyManager manager;
        int LastFocusedRowHandle;

        public xfrmCustomers()
        {
            InitializeComponent();
        }

        private void xfrmCustomers_Load(object sender, EventArgs e)
        {
            LastFocusedRowHandle = -1;
            FormLoad();
        }

        void FormLoad()
        {
            dsCustomer1.Customer.Clear();
            List<Customer> customers = customerManager.GetAllCustomer().ToList();
            if (customers.Count <= 0)
            {
                btnSave.Enabled = false;
                btnDelete.Enabled = false;
            }
            DataTable dtCustomers = EnumerableExtension.ToDataTable(customers);
            dtCustomers.TableName = "Customer";
            foreach (DataRow item in dtCustomers.Rows)
            {
                dsCustomer1.Customer.LoadDataRow(item.ItemArray, LoadOption.OverwriteChanges);
            }
            dsCustomer1.Customer.PrimaryKey = new DataColumn[] { dsCustomer1.Customer.Columns["Id"] };

            manager = dataLayoutControl1.BindingContext[dataLayoutControl1.DataSource, dataLayoutControl1.DataMember] as CurrencyManager;

            InitValidationRules();
        }

        private void InitValidationRules()
        {
            // <notEmptyTextEdit> 
            ConditionValidationRule notEmptyValidationRule = new ConditionValidationRule();
            notEmptyValidationRule.ConditionOperator = ConditionOperator.IsNotBlank;
            notEmptyValidationRule.ErrorText = "Lütfen değer giriniz";
            // </notEmptyTextEdit>

            // <notSelectValidationRule>
            ConditionValidationRule notSelectValidationRule = new ConditionValidationRule();
            notSelectValidationRule.ConditionOperator = ConditionOperator.NotEquals;
            notSelectValidationRule.Value1 = null;
            notSelectValidationRule.ErrorText = "Lütfen seçiniz";
            // </notSelectValidationRule>

            //notEmptyValidationRule
            dxValidationProvider1.SetValidationRule(FullNameTextEdit, notEmptyValidationRule);
            //dxValidationProvider1.SetValidationRule(TelephoneTextEdit, notEmptyValidationRule);
            //dxValidationProvider1.SetValidationRule(AddressMemoExEdit, notEmptyValidationRule);

            //dxValidationProvider1.ValidationMode = ValidationMode.Auto;
        }

        private void grdSearch_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            RowChanged(e.FocusedRowHandle);
        }

        void RowChanged(int FocusedRowHandle)
        {
            manager.CancelCurrentEdit();
            btnNew.Enabled = true;
            btnDelete.Enabled = true;
            btnSave.Enabled = true;

            if (grdSearch.DataRowCount <= 0)
            {
                btnSave.Enabled = false;
                btnDelete.Enabled = false;
            }

            if (FocusedRowHandle >= 0)
            {
                DataRow dr = grdSearch.GetDataRow(FocusedRowHandle);
                int id = Convert.ToInt32(dr["Id"]);
                if (id >= 0)
                {

                    if (string.IsNullOrEmpty(dsCustomer1.Customer.DefaultView.Sort))
                    {
                        dsCustomer1.Customer.DefaultView.Sort = "Id";
                    }

                    DataRowView[] drwList = dsCustomer1.Customer.DefaultView.FindRows(id);

                    if (drwList != null && drwList.Length > 0)
                    {
                        int i = 0;
                        foreach (DataRowView drw in manager.List)
                        {
                            if (drw.Row == drwList[0].Row)
                            {
                                manager.Position = i;
                                break;
                            }
                            i++;
                        }
                    }
                }

                dxValidationProvider1.Validate();
            }

        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            manager.AddNew();
            grdMaster.Enabled = false;
            btnNew.Enabled = false;
            btnDelete.Enabled = true;
            btnSave.Enabled = true;
            IdTextEdit.Text = "0";
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            DialogResult ds = MessageBox.Show("Silmek istediğize emin misiniz?", "?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (ds != DialogResult.Yes || manager.Position == -1)
            {
                return;
            }

            DataRowView drv = (DataRowView)manager.Current;
            if (drv.Row.RowState != DataRowState.Detached)
            {
                drv.Row.SetModified();
                DataTable dtDeletedCustomers = dsCustomer1.Customer.GetChanges(DataRowState.Modified);
                List<Customer> retList = EnumerableExtension.ToList<Customer>(dtDeletedCustomers);
                if (retList.Count == 1)
                {
                    foreach (Customer item in retList)
                    {
                        bool result = customerManager.DeleteCustomer(item);
                    }
                }

                LastFocusedRowHandle = grdSearch.FocusedRowHandle - 1;
                FormLoad();
                grdSearch.FocusedRowHandle = LastFocusedRowHandle;
            }
            else
            {
                manager.CancelCurrentEdit();
            }
            RowChanged(grdSearch.FocusedRowHandle);
            grdMaster.Enabled = true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!dxValidationProvider1.Validate() || dxErrorProvider1.HasErrors)
            {
                return;
            }
            manager.EndCurrentEdit();

            DataRowView drv = (DataRowView)manager.Current;

            if (drv.Row.RowState == DataRowState.Added)
            {
                DataTable dtAddedProducts = drv.Row.Table.GetChanges(DataRowState.Added);
                List<Customer> retList = EnumerableExtension.ToList<Customer>(dtAddedProducts);

                foreach (Customer item in retList)
                {
                    int id = customerManager.SaveCustomer(item);

                }
                LastFocusedRowHandle = dsCustomer1.Customer.Count - 1;
                FormLoad();
                grdSearch.FocusedRowHandle = LastFocusedRowHandle;
            }
            else if (drv.Row.RowState == DataRowState.Modified)
            {
                DataTable dtEditedProducts = drv.Row.Table.GetChanges(DataRowState.Modified);
                List<Customer> retList = EnumerableExtension.ToList<Customer>(dtEditedProducts);

                foreach (Customer item in retList)
                {
                    bool result = customerManager.UpdateCustomer(item);
                }
                LastFocusedRowHandle = grdSearch.FocusedRowHandle;
                FormLoad();
                grdSearch.FocusedRowHandle = LastFocusedRowHandle;
            }
            else if (drv.Row.RowState == DataRowState.Deleted)
            {

            }

            grdMaster.Enabled = true;
            btnNew.Enabled = true;
            btnDelete.Enabled = true;
            btnSave.Enabled = true;
        }
    }
}